package com.sth.uncenter.controller;


import com.sth.base.exceptionHandler.SthException;
import com.sth.commonutils.JwtUtils;
import com.sth.commonutils.R;
import com.sth.commonutils.ordervo.UcenterMemberOrder;
import com.sth.uncenter.entity.UcenterMember;
import com.sth.uncenter.entity.vo.RegisterVo;
import com.sth.uncenter.service.UcenterMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author sth
 * @since 2020-12-13
 */
@RestController
@CrossOrigin
@RequestMapping("/educenter/member")
@Api(description = "登录和注册")
public class UcenterMemberController {
    @Autowired
    private UcenterMemberService memberService;

    //登录
    @PostMapping("login")
    @ApiOperation(value = "会员登录")
    public R loginUser(@RequestBody UcenterMember member) {
        // 调用service 实现登录
        // 返回token 值, 使用jwt生成
        String token = memberService.login(member);
        return R.ok().data("token", token);
    }

    @ApiOperation(value = "会员注册")
    @PostMapping("register")
    public R register(@RequestBody RegisterVo registerVo) {
        memberService.register(registerVo);
        return R.ok();
    }

    @ApiOperation(value = "根据token获取登录信息")
    @GetMapping("getMemberInfo")
    public R getLoginInfo(HttpServletRequest request) {
        try {
            String memberId = JwtUtils.getMemberIdByJwtToken(request);
            UcenterMember loginInfoVo = memberService.getLoginInfo(memberId);
            return R.ok().data("item", loginInfoVo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SthException(20001, "error");
        }
    }

    // 根据用户id获取用户信息
    @PostMapping("getUserInfoOrder/{id}")
    public UcenterMemberOrder getUserInfoOrder(@PathVariable String id) {
        UcenterMember member = memberService.getById(id);
        UcenterMemberOrder ucenterMemberOrder = new UcenterMemberOrder();
        BeanUtils.copyProperties(member, ucenterMemberOrder);
        return ucenterMemberOrder;
    }

    // 统计分析 -> 某一天的注册人数
    @GetMapping("countRegister/{day}")
    public R countRegister(@PathVariable String day) {
        Integer count = memberService.countRegister(day);
        return R.ok().data("countRegister", count);
    }

}

